package com.example.androidstudy.ui.demo.bezier

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.Point
import android.util.AttributeSet
import android.view.View
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.toArgb
import androidx.core.content.contentValuesOf
import androidx.core.util.rangeTo
import com.example.androidstudy.R
import java.lang.Math.pow
import kotlin.math.pow

class BezierShowView @JvmOverloads constructor(
    context: Context,
    val attrs: AttributeSet? = null,
    val defStyleAttr: Int = 0,
    val defStyleRes: Int = 0

) : View(context, attrs, defStyleAttr, defStyleRes) {

    var drawable = context.getDrawable(R.drawable.circle)
    var start = Point(10, 90)
    var end = Point(90, 90)
    var controls = arrayListOf(Point(50, 0))
    var paint = Paint().apply {
        color = Color.Blue
        style = PaintingStyle.Fill
        isAntiAlias = true
        strokeWidth = 1f

    }.asFrameworkPaint()
    var startPaint = Paint().apply {
        color = Color.Red
        isAntiAlias = true
        style = PaintingStyle.Stroke
        strokeWidth = 1f
    }.asFrameworkPaint()

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.save()
//        canvas.drawColor(Color.Cyan.toArgb())
        canvas.scale(width / 100f, height / 100f)
        sequence {
            repeat(100) {
                yield(0.01f * it)
            }
        }.forEach { t ->
            val x =
                start.x * (1 - t).pow(2f) + end.x * t
                    .pow(2f) + 2 * t * (1 - t) * controls[0].x
            val y =
                start.y * (1 - t).pow(2f) + end.y * t
                    .pow(2f) + 2 * t * (1 - t) * controls[0].y
            canvas.drawPoint(x, y, paint)
        }
     /*   canvas.drawPath(Path().apply {
            moveTo(start.x.toFloat(),start.y.toFloat())
            quadTo(
                controls[0].x.toFloat(), controls[0].y.toFloat(),
                end.x.toFloat(), end.y.toFloat()
            )
        }, startPaint)*/
        canvas.drawPoint(start.x.toFloat(), start.y.toFloat(), startPaint)
        canvas.drawPoint(end.x.toFloat(), end.y.toFloat(), startPaint)
        canvas.drawCircle(end.x.toFloat(), end.y.toFloat(), 2f, startPaint)
        canvas.drawCircle(start.x.toFloat(), start.y.toFloat(), 2f, startPaint)
        canvas.restore()

    }
}